from django.shortcuts import render, HttpResponse, redirect
from crm_app import models
from django.conf import settings
from rbac.service.init_permission import init_permission


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')

    username= request.POST.get("user")
    password= request.POST.get("pwd")

    if not all([username, password]):
        return HttpResponse("请填写用户名或密码")

    user_obj = models.UserInfo.objects.filter(username=username, password=password).first()
    if not user_obj:
        return render(request, "login.html", {"msg": "用户名或密码错误"})

    # 用户信息放入session中
    request.session["userinfo"] = {"id": user_obj.id, "name": user_obj.name}

    # 权限信息初始化
    init_permission(user_obj, request)

    return redirect("/stark/crm_app/course/list")